package com.sms.controller;

import com.sms.mapper.DepartmentMapper;
import com.sms.mapper.EmployeeMapper;

import com.sms.pojo.Department;
import com.sms.pojo.Employee;
import com.sms.service.DepartmentService;
import com.sms.service.EmployeeService;
import com.sms.service.impl.DepartmentServiceImpl;
import com.sms.service.impl.EmployeeServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.Collection;
import java.util.List;

@Controller
public class EmployeeController {

    @Autowired
    EmployeeServiceImpl employeeService;
    @Autowired
    DepartmentServiceImpl departmentService;

    @RequestMapping("/emps")
    public String list(Model model){
        List<Employee> employees = employeeService.getAll();
        model.addAttribute("emps",employees);
        return "emp/list";
    }

    @GetMapping("/emp")
    public String toAddpage(Model model){
        //查出所有部门的信息
        List<Department> departments = departmentService.getDepartments();
        model.addAttribute("departments",departments);
        return "emp/add";
    }

    @PostMapping("/emp")
    public String addEmp(Employee employee){
        //添加的操作
        employee.setDepartmentName(departmentService.getDepatmentById(employee.getDepartment().getId()).getDepartmentName());
//        System.out.println("DeBug=>"+employee);
        employeeService.save(employee);//保存员工的信息
        return "redirect:/emps";
    }

    //去员工的修改页面
    @GetMapping("/emp/{id}")
    public String toUpdateEmp(@PathVariable("id")Integer id,Model model){
        //查出原来的数据
        Employee employee = employeeService.getEmployeeById(id);
        employee.setDepartment(departmentService.getDepatmentByName(employee.getDepartmentName()));
//        System.out.println("DeBug=>"+employee);
        model.addAttribute("emp",employee);
        List<Department> departments = departmentService.getDepartments();
//        System.out.println("DeBug=>"+departments);
        model.addAttribute("departments",departments);
        return "emp/update";
    }

    @PostMapping("/updateEmp")
    public String updateEmp(Employee employee){
        employee.setDepartmentName(departmentService.getDepatmentById(employee.getDepartment().getId()).getDepartmentName());
//        System.out.println("DeBug=>"+employee);
        employeeService.update(employee);
        return "redirect:/emps";
    }

    //删除员工
    @GetMapping("/delemp/{id}")
    public String deleteEmp(@PathVariable("id")int id){
        employeeService.deleteById(id);
        return "redirect:/emps";
    }
}
